const parser = require('./parser');
const getRichTextNodes = require('./richtext').getRichTextNodes;

Component({
  properties: {
    md: {
      type: String,
      value: '',
      observer() {
        this.parseMd();
      }
    },
    scroll: {
      type: String,
      value: '',
      observer(val) {
        this.scrollInto(val)
      }
    },
    type: {
      type: String,
      value: 'wemark'
    },
    link: {
      type: Boolean,
      value: false
    },
    highlight: {
      type: Boolean,
      value: false
    }
  },
  data: {
    parsedData: {},
    richTextNodes: [],
  },
  methods: {
    handleUrlClick(e) {
      wx.setClipboardData({
        data: e.currentTarget.dataset.url,
        success() {
          wx.showToast({
            title: '小程序不支持链接跳转，链接已复制',
            icon: 'none'
          })
        }
      })
    },

    scrollInto(val) {
      const query = wx.createSelectorQuery().in(this)
      let that = this
      query.select('#' + val).boundingClientRect()

      query.selectViewport().scrollOffset()
      query.exec(function (res) {
        that.triggerEvent('jump', {
          top: res[0].top
        })
      })
    },

    handleCopyCode(e) {
      let info = e.currentTarget.dataset.info
      if (info.type && info.type === 'code' && info.content !== undefined) {
        const code = info.isArray ? info.content.map(item => item.content || item).join('') : info.content
        wx.setClipboardData({
          data: code,
          success() {
            wx.showToast({
              title: '代码已复制',
              icon: 'none'
            })
          }
        })
      }
    },

    parseMd() {
      if (this.data.md) {
        var parsedData = parser.parse(this.data.md, {
          link: this.data.link,
          highlight: this.data.highlight
        });


        // console.log('parsedData:', parsedData);
        let keyarr = []
        if (this.data.type === 'wemark') {
          for (let i = 0; i < parsedData.length; i++) {
            if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(parsedData[i]['type'])) {
              let tale = parsedData[i]['type'] + '_' + i,
                content = ''
              if (parsedData[i]['content'] && parsedData[i]['content'] instanceof Array && parsedData[i]['content'][0] && parsedData[i]['content'][0]['content']) {
                content = parsedData[i]['content'][0]['content']
              }
              parsedData[i].tale = tale
              keyarr.push({
                type: parsedData[i]['type'],
                tale,
                content
              })
            }
          }

          this.setData({
            parsedData
          });

          this.triggerEvent('tale', {
            tale: keyarr
          })



        } else {
          // var inTable = false;
          var richTextNodes = getRichTextNodes(parsedData);

          // console.log('richTextNodes:', richTextNodes);

          this.setData({
            richTextNodes
          });




          /* // 分批更新
          var update = {};
          var batchLength = 1000;
          console.log(batchLength);
          for(var i=0; i<richTextNodes.length; i++){
          	update['richTextNodes.' + i] = richTextNodes[i];
          	if(i%batchLength === batchLength - 1){
          		console.log(update);
          		this.setData(update);
          		update = {};
          	}
          }
          this.setData(update);
          update = {}; */
        }

      }
    }
  }
});